package com.bj.disc.ui.login.fragment

import android.Manifest
import android.content.Context
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.ai3d.rfid.R
import com.ai3d.rfid.base.app.App
import com.ai3d.rfid.base.fragment.BaseVmVdbFragment
import com.ai3d.rfid.common.event.EventMgs
import com.ai3d.rfid.common.libs.InitLanguage
import com.ai3d.rfid.common.log.Logcat
import com.ai3d.rfid.common.proxy.MMKVProxy
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_DF_GAME_RESET
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_OC_GAME_RESET
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_SETTINGS_LANGUAGE_ASSIST
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_SETTINGS_LANGUAGE_MAIN
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_TOKEN
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_UOT_GAME_RESET
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_USER_ID
import com.ai3d.rfid.common.proxy.ToastProxy
import com.ai3d.rfid.common.utils.HandlerUtils
import com.ai3d.rfid.databinding.FragmentLoginBinding
import com.bj.disc.dialog.RequestPermissionsDialog
import com.bj.disc.activity.MainActivity
import com.bj.disc.database.EventReq
import com.bj.disc.ui.login.activity.RegisterActivity
import com.bj.disc.ui.login.bean.LoginReq
import com.bj.disc.ui.login.bean.LoginResp
import com.bj.disc.ui.login.dialog.LanguagePop
import com.bj.disc.ui.login.dialog.LanguagePop.Companion.SHOW_TYPE_ASSIST_LANGUAGE
import com.bj.disc.ui.login.dialog.LanguagePop.Companion.SHOW_TYPE_MAIN_LANGUAGE
import com.bj.disc.ui.login.utils.FocusUtils
import com.bj.disc.ui.login.utils.RegexUtils
import com.bj.disc.ui.login.vm.LoginViewModel
import com.bj.disc.util.DiscConstants
import com.bj.disc.util.DiscConstants.HEADER_CONTENT_LANGUAGE_CANTONESE
import com.bj.disc.util.DiscConstants.HEADER_CONTENT_LANGUAGE_EN_US
import com.bj.disc.util.DiscConstants.HEADER_CONTENT_LANGUAGE_HOKKIEN
import com.bj.disc.util.DiscConstants.HEADER_CONTENT_LANGUAGE_MALAY
import com.bj.disc.util.DiscConstants.HEADER_CONTENT_LANGUAGE_TAMIL
import com.bj.disc.util.DiscConstants.HEADER_CONTENT_LANGUAGE_ZH_CN
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.permissionx.guolindev.PermissionX
import com.ym521.logdog.LogDog


/**
 * @ProjectName : Kolb
 * @Author : weijinsong
 * @Time : 2023/1/4 16:53
 * @Description : 登录
 */
class LoginFragment : BaseVmVdbFragment<LoginViewModel, FragmentLoginBinding>() {
    private val TAG = "LoginFragment"
    val action: Action by lazy { Action() }


    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mDatabind.action = action
        mDatabind.edtAccount.postDelayed({
                        hideSoftKeyboard(requireActivity())
                        setCacheData()
                                 }, 200)
    }

    override fun initData() {
        super.initData()
//        mDatabind.etLogin.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
//        mDatabind.etLogin.transformationMethod = PasswordTransformationMethod.getInstance()


        when (MMKVProxy.getString(KEY_SETTINGS_LANGUAGE_MAIN, HEADER_CONTENT_LANGUAGE_EN_US)) {
            HEADER_CONTENT_LANGUAGE_EN_US -> {
                mDatabind.tvMainLanguage.setText(R.string.english)
            }
            HEADER_CONTENT_LANGUAGE_ZH_CN -> {
                mDatabind.tvMainLanguage.setText(R.string.chinese)
            }
            HEADER_CONTENT_LANGUAGE_HOKKIEN -> {
                mDatabind.tvMainLanguage.setText(R.string.hokkien)
            }
            HEADER_CONTENT_LANGUAGE_CANTONESE -> {
                mDatabind.tvMainLanguage.setText(R.string.cantonese)
            }
            HEADER_CONTENT_LANGUAGE_TAMIL -> {
                mDatabind.tvMainLanguage.setText(R.string.tamil)
            }
            HEADER_CONTENT_LANGUAGE_MALAY -> {
                mDatabind.tvMainLanguage.setText(R.string.malay_lan)
            }
        }

        when (MMKVProxy.getString(KEY_SETTINGS_LANGUAGE_ASSIST, HEADER_CONTENT_LANGUAGE_EN_US)) {
            HEADER_CONTENT_LANGUAGE_EN_US -> {
                mDatabind.tvAssistLanguage.setText(R.string.english)
            }
            HEADER_CONTENT_LANGUAGE_ZH_CN -> {
                mDatabind.tvAssistLanguage.setText(R.string.chinese)
            }
            HEADER_CONTENT_LANGUAGE_HOKKIEN -> {
                mDatabind.tvAssistLanguage.setText(R.string.hokkien)
            }
            HEADER_CONTENT_LANGUAGE_CANTONESE -> {
                mDatabind.tvAssistLanguage.setText(R.string.cantonese)
            }
            HEADER_CONTENT_LANGUAGE_TAMIL -> {
                mDatabind.tvAssistLanguage.setText(R.string.tamil)
            }
            HEADER_CONTENT_LANGUAGE_MALAY -> {
                mDatabind.tvAssistLanguage.setText(R.string.malay_lan)
            }
        }


        mDatabind.llMainLanguage.setOnClickListener {
            LanguagePop(requireActivity(), SHOW_TYPE_MAIN_LANGUAGE, mViewModel.account.value, mViewModel.password.value) {
                mDatabind.tvMainLanguage.setText(it)
            }.show(mDatabind.llMainLanguage)
        }

        mDatabind.llAssistLanguage.setOnClickListener {
            LanguagePop(requireActivity(), SHOW_TYPE_ASSIST_LANGUAGE, mViewModel.account.value, mViewModel.password.value) {
                mDatabind.tvAssistLanguage.setText(it)
            }.show(mDatabind.llAssistLanguage)
        }

        mDatabind.cbOc.isChecked = MMKVProxy.getBoolean(KEY_OC_GAME_RESET, false)
        mDatabind.cbDf.isChecked = MMKVProxy.getBoolean(KEY_DF_GAME_RESET, false)
        mDatabind.cbUot.isChecked = MMKVProxy.getBoolean(KEY_UOT_GAME_RESET, false)

        mDatabind.cbOc.setOnCheckedChangeListener { compoundButton, b ->
            Logcat.d(TAG, "oc b : $b")
            MMKVProxy.setBoolean(KEY_OC_GAME_RESET, b)
        }

        mDatabind.cbDf.setOnCheckedChangeListener { compoundButton, b ->
            Logcat.d(TAG, "df b : $b")
            MMKVProxy.setBoolean(KEY_DF_GAME_RESET, b)

        }

        mDatabind.cbUot.setOnCheckedChangeListener { compoundButton, b ->
            Logcat.d(TAG, "uot b : $b")
            MMKVProxy.setBoolean(KEY_UOT_GAME_RESET, b)
        }
        requestPermission()
    }

    private fun requestPermission() {
        val hasRecordAudioPermission =
            PermissionX.isGranted(App.instance, Manifest.permission.RECORD_AUDIO)
        if (hasRecordAudioPermission) {
        } else {
            RequestPermissionsDialog(
                RequestPermissionsDialog.RECORD_AUDIO_PERMISSIONS,
                requireActivity()
            ) {
                if (it) {
                    PermissionX.init(requireActivity())
                        .permissions(
                            Manifest.permission.RECORD_AUDIO,
                        )
                        .onExplainRequestReason { deniedList ->
                        }
                        .request { allGranted, grantedList, deniedList ->
                            if (allGranted) {
                            } else {
                                ToastProxy.showShort(R.string.permission_record_audio_request)
                            }
                        }
                } else {
                    ToastProxy.showShort(R.string.permission_record_audio_request)
                }

            }.show()
        }
    }

    override fun createObserver() {
        mViewModel.loginResp.observe(this) {
            MMKVProxy.setString(MMKVProxy.USER_NAME, it.userName)
            mViewModel.password.value?.let { it1 -> MMKVProxy.setString(MMKVProxy.USER_PWD, it1) }
            gotoMain(it)
        }
    }

    override fun onResume() {
        super.onResume()
        if(mDatabind != null && mDatabind.edtAccount != null){
            setCacheData()
        }
        hideSoftInput()
    }

    override fun onPause() {
        super.onPause()
        arguments?.let {
           it.putString("account", mViewModel.account.value)
           it.putString("password", mViewModel.password.value)
        }
    }

    private fun setCacheData(){
        //切换语言的时候传递过来的account和password不为空  第一次启动应用、其他情况再次回到登录页都为空
        if(arguments?.getString("account") != null || arguments?.getString("password") != null){
            mViewModel.account.value = requireArguments().getString("account")
            mViewModel.password.value = requireArguments().getString("password")
        }else{
            if (MMKVProxy.getString(MMKVProxy.USER_NAME, "").isNotEmpty()) {
                mViewModel.account.value = MMKVProxy.getString(MMKVProxy.USER_NAME, "")
            }
            if (MMKVProxy.getString(MMKVProxy.USER_PWD, "").isNotEmpty()) {
                mViewModel.password.value = MMKVProxy.getString(MMKVProxy.USER_PWD, "")
            }
            mDatabind.executePendingBindings()
        }
    }

    private fun hideSoftInput(){
        if(mDatabind != null && mDatabind.edtAccount != null && mDatabind.edtPassword != null){
            (activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?)?.let {
                it.hideSoftInputFromWindow(mDatabind.edtAccount.windowToken, 0) // 强制隐藏键盘
                it.hideSoftInputFromWindow(mDatabind.edtPassword.windowToken, 0) // 强制隐藏键盘
            }
        }
    }

    private fun gotoMain(loginResp: LoginResp) {
        MMKVProxy.setString(KEY_TOKEN, loginResp.token)
        MMKVProxy.setString(KEY_USER_ID, loginResp.userId)
        var eventReq = EventReq().apply {
            gameName = null
            level = null
            stage = null
            stageType = null
            sessionId = null
            eventType = DiscConstants.EVENT_TYPE_LOGIN
            gameSessionId = null
            levelSessionId = null
            theme = null
        }
        LogDog.debug(TAG,"putCache上报事件:"+ GsonUtils.toJson(eventReq))
        EventMgs.putCache(eventReq)
        MainActivity.startMainActivity(requireActivity())
    }

    override fun onDestroy() {
        super.onDestroy()
        HandlerUtils.removeCallbacksAndMessages()
    }


    inner class Action {
        fun logout() {
//            activity?.finish()
            InitLanguage.finishAll()
        }

        fun clear() {
            mViewModel.account.value = ""
            mViewModel.password.value = ""
        }

        fun login(v: View) {
            LogUtils.a(v)
            when {
                mViewModel.account.value?.isEmpty() == true -> {
                    FocusUtils.requestFocus(mDatabind.edtAccount)
                    ToastProxy.showLong(R.string.please_enter_your_phone_or_email)
                    //showMessage(R.string.please_enter_your_phone_or_email)
                }
//                !RegexUtils.isEmail(mViewModel.account.value) && !RegexUtils.isPhone(mViewModel.account.value) -> {
//                    FocusUtils.requestFocus(mDatabind.edtAccount)
//                    ToastProxy.showLong(R.string.phone_or_email_incorrect_format)
//                    //showMessage(R.string.phone_or_email_incorrect_format)
//                }
                mViewModel.password.value?.isEmpty() == true -> {
                    FocusUtils.requestFocus(mDatabind.edtPassword)
                    ToastProxy.showLong(R.string.please_fill_in_the_password)
                    //showMessage(
//                    R.string.please_fill_in_the_password
//                )
                }
                !RegexUtils.isPwdRegex(mViewModel.password.value) -> {
                    FocusUtils.requestFocus(mDatabind.edtPassword)
                    ToastProxy.showLong(R.string.only_8_12_letters_number_and_underscores_can_be_entered_for_the_password)
                    //showMessage(
//                    R.string.password_must_be_8_20_letters_number_or_special_characters
//                )
                }
                else -> {
                    mViewModel.login(
                        LoginReq().apply {
                            userName = mViewModel.account.value!!
                            password = mViewModel.password.value!!
                        }
                    )
                }
            }
        }

        fun toggleShowPwd() {
            mViewModel.isShowPwd.value = (!mViewModel.isShowPwd.value!!)
            LogUtils.e(mViewModel.isShowPwd.value)
            mDatabind.edtPassword.transformationMethod = when (mViewModel.isShowPwd.value) {
                true -> HideReturnsTransformationMethod.getInstance()
                else -> PasswordTransformationMethod.getInstance()
            }
            mDatabind.edtPassword.setSelection(mDatabind.edtPassword.text.length)
        }

        fun gotoForgetPwd() {
            hideSoftKeyboard(activity)
            clear()
//            ForgetPwdActivity.startForgetActivity(
//                requireActivity(),
//                mDatabind.edtAccount.text.toString()
//            )
        }

        fun register() {
            activity?.let { RegisterActivity.startRegisterActivity(it) }
        }
    }
}